let postId;
document.addEventListener('DOMContentLoaded', async () => {
    const urlParams = new URLSearchParams(window.location.search);
    postId = urlParams.get('id');

    if (!postId) {
        Swal.fire({
            icon: 'error',
            title: '错误',
            text: '文章不存在！',
            confirmButtonColor: '#546d9e'
        });
        window.location.href = 'blog.html';
        return;
    }

    const renderer = new marked.Renderer();

    const languageMap = {
        'javascript': 'JavaScript',
        'typescript': 'TypeScript',
        'html': 'HTML',
        'css': 'CSS',
        'java': 'Java',
        'python': 'Python',
        'cpp': 'C++',
        'c': 'C',
        'csharp': 'C#',
        'go': 'Go',
        'rust': 'Rust',
        'sql': 'SQL',
        'json': 'JSON',
        'xml': 'XML',
        'yaml': 'YAML',
        'bash': 'Bash',
        'shell': 'Shell',
        'plaintext': '纯文本',
        'markdown': 'Markdown',
        'nginx': 'Nginx',
        'dockerfile': 'Dockerfile',
        'properties': '配置',
        'js': 'JavaScript',
        'ts': 'TypeScript',
        'py': 'Python',
        'rs': 'Rust'
    };

    // 自定义代码块渲染
    renderer.code = function (code, language) {
        // 优先使用 Markdown 中指定的语言，否则自动检测
        let detectedLanguage = language || hljs.highlightAuto(code).language || 'plaintext';
        detectedLanguage = detectedLanguage.toLowerCase();

        // 获取显示名称
        const displayName = languageMap[detectedLanguage] || detectedLanguage;

        // 高亮代码
        let highlightedCode;
        try {
            if (language) {
                highlightedCode = hljs.highlight(code, {
                    language: detectedLanguage
                }).value;
            } else {
                highlightedCode = hljs.highlightAuto(code).value;
            }
        } catch (e) {
            console.warn('代码高亮失败:', e);
            highlightedCode = code;
        }

        // 生成唯一ID用于复制功能
        const blockId = `code-block-${Math.random().toString(36).substr(2, 9)}`;

        return `
            <div class="code-block" id="${blockId}">
                <div class="code-header">
                    <span class="code-language">${displayName}</span>
                    <button class="copy-btn" onclick="copyCode('${blockId}')">
                        <i class="far fa-copy"></i>
                    </button>
                </div>
                <div class="code-content">
                    <pre><code class="hljs language-${detectedLanguage}">${highlightedCode}</code></pre>
                </div>
            </div>
        `;
    };

    // 自定义表格渲染
    renderer.table = function (header, body) {
        return `
            <div class="table-wrapper">
                <table>
                    <thead>${header}</thead>
                    <tbody>${body}</tbody>
                </table>
            </div>
        `;
    };

    marked.setOptions({
        renderer: renderer,
        gfm: true,
        breaks: true,
        highlight: function (code, lang) {
            if (lang && hljs.getLanguage(lang)) {
                return hljs.highlight(code, { language: lang }).value;
            }
            return hljs.highlightAuto(code).value;
        }
    });

    try {
        const response = await request.get(`/post/${postId}`);
        const post = response.data;

        document.title = `${post.title} - 文章详情`;
        document.querySelector('.post-title').textContent = post.title;
        document.querySelector('.author-name').textContent = post.user.nickname || post.user.username;
        document.querySelector('.time-text').textContent = new Date(post.createTime).toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        });

        // 更新浏览量和点赞数到页面和 sessionStorage
        const viewCount = document.querySelector('.view-count');
        const likeCount = document.querySelector('.like-count');

        viewCount.textContent = `👁️ ${post.views}`;
        likeCount.textContent = `❤️ ${post.likes}`;

        // 立即更新到 sessionStorage
        sessionStorage.setItem(`post_${postId}_views`, post.views);
        sessionStorage.setItem(`post_${postId}_likes`, post.likes);

        // 渲染文章内容
        const content = marked.parse(post.content);
        document.querySelector('.post-content').innerHTML = content;

        // 点赞功能
        let isAnimating = false;

        function createLikeEffect() {
            // 创建粒子容器
            const particlesContainer = document.createElement('div');
            particlesContainer.className = 'like-particles';
            likeCount.appendChild(particlesContainer);

            // 创建波纹效果
            const ripple = document.createElement('div');
            ripple.className = 'ripple';
            particlesContainer.appendChild(ripple);

            // 创建粒子
            for (let i = 0; i < 8; i++) {
                const particle = document.createElement('div');
                particle.className = 'particle';

                // 随机生成粒子的运动方向和旋转角度
                const angle = (i * 45) + Math.random() * 30;
                const distance = 20 + Math.random() * 20;
                const tx = Math.cos(angle * Math.PI / 180) * distance;
                const ty = Math.sin(angle * Math.PI / 180) * distance;
                const rotation = Math.random() * 360;

                particle.style.setProperty('--tx', `${tx}px`);
                particle.style.setProperty('--ty', `${ty}px`);
                particle.style.setProperty('--r', `${rotation}deg`);

                particlesContainer.appendChild(particle);
            }

            // 动画结束后清理
            setTimeout(() => {
                particlesContainer.remove();
            }, 600);
        }

        likeCount.addEventListener('click', async () => {
            if (isAnimating) return;

            try {
                isAnimating = true;
                likeCount.classList.add('liked');
                createLikeEffect();

                const response = await request.post(`/post/${postId}/like`);
                if (response.code === 200) {
                    const { likeCount: newLikes } = response.data;
                    likeCount.textContent = `❤️ ${newLikes}`;
                    sessionStorage.setItem(`post_${postId}_likes`, newLikes);

                    Swal.fire({
                        icon: 'success',
                        title: '点赞成功！',
                        showConfirmButton: false,
                        timer: 1000,
                        position: 'top-end',
                        toast: true
                    });
                }
            } catch (error) {
                console.error('点赞失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '点赞失败',
                    text: '请稍后重试',
                    confirmButtonColor: '#546d9e'
                });
            } finally {
                setTimeout(() => {
                    likeCount.classList.remove('liked');
                    isAnimating = false;
                }, 800);
            }
        });

        // 添加 Giscus 评论
        const giscusScript = document.createElement('script');
        giscusScript.src = "https://giscus.app/client.js";
        giscusScript.setAttribute('data-repo', "FlameCCG/CCG003_MJ");
        giscusScript.setAttribute('data-repo-id', "R_kgDONjvPPQ");
        giscusScript.setAttribute('data-category', "General");
        giscusScript.setAttribute('data-category-id', "DIC_kwDONjvPPc4ClmaM");
        giscusScript.setAttribute('data-mapping', "specific");
        giscusScript.setAttribute('data-term', `post-${postId}`);
        giscusScript.setAttribute('data-strict', "0");
        giscusScript.setAttribute('data-reactions-enabled', "1");
        giscusScript.setAttribute('data-emit-metadata', "0");
        giscusScript.setAttribute('data-input-position', "bottom");
        giscusScript.setAttribute('data-theme', "light");
        giscusScript.setAttribute('data-lang', "zh-CN");
        giscusScript.setAttribute('crossorigin', "anonymous");
        giscusScript.async = true;

        document.querySelector('.giscus').appendChild(giscusScript);

    } catch (error) {
        console.error('获取文章详情失败：', error);
        Swal.fire({
            icon: 'error',
            title: '加载失败',
            text: '获取文章详情失败，请稍后重试',
            confirmButtonColor: '#546d9e'
        });
    }
});

// 复制代码功能
function copyCode(blockId) {
    const codeBlock = document.getElementById(blockId);
    const code = codeBlock.querySelector('code').innerText;
    const copyBtn = codeBlock.querySelector('.copy-btn i');

    navigator.clipboard.writeText(code).then(() => {
        // 更改图标为成功状态
        copyBtn.className = 'fas fa-check';

        Swal.fire({
            icon: 'success',
            title: '复制成功',
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 1500
        });

        setTimeout(() => {
            copyBtn.className = 'far fa-copy';
        }, 2000);
    }).catch(() => {
        Swal.fire({
            icon: 'error',
            title: '复制失败',
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 1500
        });
    });
} 